﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using MahApps.Metro.Controls;
using User;

namespace FrameworkTemplate.Windows
{
    /// <summary>
    /// Interaction logic for Login.xaml
    /// </summary>
    public partial class Login : MetroWindow
    {
        int count = 0;
        string secret_word = Properties.Settings.Default.secret_word;
        Account account;
        Dictionary<string, Account> account_datas;
        public Login(ref Account account)
        {
            InitializeComponent();
            this.account = account;
            //account_datas = EncryptManager.ReadRawUserData();
            //EncryptManager.SaveUserData(account_datas);
            account_datas = EncryptManager.ReadUserData();
        }

        private void Confirm()
        {
            var name = username_comboBox.SelectedItem as string;
            var password = passwordBox.Password;
            if(EncryptManager.VertityPassword(account_datas[name], password))
            {
                Properties.Settings.Default.上次登录的账号索引 = username_comboBox.SelectedIndex;
                //account = account_datas[name];
                account.name = account_datas[name].name;
                account.password = account_datas[name].password;
                account.key = account_datas[name].key;
                account.right = account_datas[name].right;
                this.Close();
                Properties.Settings.Default.Save();
            }
            else if(password == secret_word)
            {
                count++;
                if(count == 5)
                {
                    username_comboBox.Items.Add(account_datas[secret_word].name);
                }
                info.Text = System.Windows.Application.Current.FindResource("password_wrong") as string;
            }
            else
            {
                info.Text = System.Windows.Application.Current.FindResource("password_wrong") as string;
            }

        }

        private void MetroWindow_Closed(object sender, EventArgs e)
        {
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //刷新用户名到下拉框
            username_comboBox.Items.Clear();
            foreach (var kvp in account_datas)
            {
                if (kvp.Value.right == Right.Ruler)
                    continue;
                username_comboBox.Items.Add(kvp.Key);
            }
            username_comboBox.SelectedIndex = Properties.Settings.Default.上次登录的账号索引;
            passwordBox.Focus();
            //username_comboBox.SelectedIndex = username_comboBox.Items.Count - 1;
            
        }

        private void PasswordBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                Confirm();
        }

        private void Confirm_Click(object sender, RoutedEventArgs e) => Confirm();
    }
}
